package com.anyun.collect

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.fragment.app.Fragment
import com.anyun.collect.extensions.active
import com.anyun.collect.extensions.attach
import com.anyun.collect.extensions.detach
import com.anyun.collect.helper.BottomNavigationPosition
import com.anyun.collect.helper.createFragment
import com.anyun.collect.helper.findNavigationPositionById
import com.anyun.collect.helper.getTag
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity() {

    private val TAG:String = MainActivity::class.java.simpleName
    private val KEY_POSITION = "keyPosition"
    private var navPosition: BottomNavigationPosition = BottomNavigationPosition.HOME

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN)
        restoreSaveInstanceState(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<BottomNavigationView>(R.id.bottom_navigation).apply {
            active(navPosition.position)
            setOnNavigationItemSelectedListener {item->
                Log.i(TAG,"itemid->"+item.itemId)
                navPosition = findNavigationPositionById(item.itemId)
                Log.i(TAG,"navPosition->"+navPosition.id)
                switchFragment(navPosition)
            }
        }
        initFragment(savedInstanceState)
    }

    private fun initFragment(savedInstanceState: Bundle?) {
        savedInstanceState ?: switchFragment(BottomNavigationPosition.HOME)
    }

    private fun restoreSaveInstanceState(savedInstanceState: Bundle?) {
        savedInstanceState?.getInt(KEY_POSITION,BottomNavigationPosition.HOME.id)?.also {
            navPosition = findNavigationPositionById(it)
        }
    }

    private fun switchFragment(navPosition: BottomNavigationPosition): Boolean {
        return findFragment(navPosition).let {
            if (it.isAdded) return false
            supportFragmentManager.detach()
            Log.i(TAG,navPosition.getTag());
            supportFragmentManager.attach(it,navPosition.getTag())
            supportFragmentManager.executePendingTransactions()
        }
    }

    private fun findFragment(navPosition: BottomNavigationPosition): Fragment {
        Log.i(TAG,"findfragment tag="+navPosition.getTag()+" navPosId="+navPosition.id)
        return supportFragmentManager.findFragmentByTag(navPosition.getTag()) ?: navPosition.createFragment()
    }
}
